package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.domain.user.UserDO;
import com.qk.dto.user.UserDTO;
import com.qk.entity.User;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@SuppressWarnings("all")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    private static final String DEFAULT_PASSWORD_SUFIX = "123";

    @Override
    public void add(User user) {

        boolean hasNull = BeanUtil.hasNullField(user, "id", "password", "roleId", "deptId", "image", "remark", "updateTime", "createTime");
        if (hasNull) {
            throw new RuntimeException("参数错误");
        }

        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());

        String rawPassword = new StringBuilder(user.getUsername()).append(DEFAULT_PASSWORD_SUFIX).toString();
        String encodedPassword=new StringBuilder(user.getUsername()).append(DEFAULT_PASSWORD_SUFIX).toString();
        user.setPassword(rawPassword);

        userMapper.insert(user);
    }

    @Override
    public PageResult<UserDO> list(UserDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());

        List<UserDO> result = userMapper.selectByPage(dto);
        Page<UserDO> page = (Page<UserDO>) result;

        page.forEach(userDO -> System.out.println(userDO));

        return PageResult.<UserDO>builder()
                .total(Long.valueOf(page.getTotal()).intValue())
                .rows(page.getResult())
                .build();
    }


    @Override
    public void update(User user) {
        user.setUpdateTime(LocalDateTime.now());
        userMapper.update(user);
    }

    @Override
    public void delete(Long id) {
        userMapper.deleteById(id);
    }

    @Override
    public User getUserById(Integer id) {
        return userMapper.selectById(id);
    }

    @Override
    public List<User> getAllUsers() {
        return userMapper.selectAllUsers();
    }

    @Override
    public List<User> getUsersByRole(String roleLabel) {
        return userMapper.getUsersByRole(roleLabel);
    }

    @Override
    public List<User> getUsersByDept(Integer deptId) {
        return userMapper.getUsersByDept(deptId);
    }
}
